package com.futureway.test.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.futureway.test.entity.QUser;
import com.futureway.test.entity.User;
import com.futureway.test.entity.UserCourse;
import com.futureway.test.service.UserCourseService;
import com.futureway.test.service.UserService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Predicate;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private UserCourseService userCourseService;

	@GetMapping("/page2")
	public void page2() {
		int pageSize = 20;
		int pageNum = 1 - 1;

		Sort sort = Sort.by(new Sort.Order(Direction.ASC, "id"));
		Pageable pageable = PageRequest.of(pageNum, pageSize, sort);

		List<Predicate> predicates = new ArrayList<>();

		predicates.add(QUser.user.userName.like("%张%"));

		QueryResults<Tuple> result = userService.page(predicates, pageable);

		log.info("result:{},data:{}", result, result.getResults());

	}

	@GetMapping("/page")
	public Page<User> page() {
		int pageSize = 20;
		int pageNum = 1 - 1;

		Sort sort = Sort.by(new Sort.Order(Direction.ASC, "id"));
		Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
		return userService.page(QUser.user.userName.like("%张%"), pageable);

	}

	@PostMapping("/course/save")
	public Boolean save(Integer userId, Integer courseId) {
		return userCourseService.save(new UserCourse(userId, courseId));
	}

	@GetMapping("/get/{id}")
	public User get(@PathVariable Integer id) {
		log.error(">>>>测试error级别");
		log.debug(">>>>测试debug级别");
		log.info(">>>>测试info级别");
		log.warn(">>>>测试warn级别");
		return userService.get(id);
	}

	@GetMapping("/list")
	public List<User> list(String userName) {
		if (StringUtils.isEmpty(userName))
			return userService.findAll();
		return userService.findAll(userName);
	}

	@PostMapping("/save")
	public Integer save(String userName) {
		return userService.save(userName);
	}

}
